<?php

namespace App\Modules\Admin\Upload;

use  App\Common\Http\Basics\Upload;
use  App\Common\Http\Basics\Success;
use  App\Services\Settings\Server as SettingServer;
use  App\Dao\Mongo\FileSlice;
use  App\Utils\Oss\StsToken;
use  App\Common\Helper;
use  App\Utils\Nanoid\Control as Nanoid;
use  App\Common\Enum\OssDirPrefix;
use  App\Utils\Uuid\Control as Uuid;
use  App\Services\Oss\Server as OssServer;
use  App\Services\Oss\Admins as AdminsOss;
use  App\Jobs\ServiceJob;
use  OSS\OssClient;
// use  App\Common\Http\Basics\Upload;

class FileModule extends \App\Modules\Admin\BaseModule
{

    public function first()
    {

        $settings = SettingServer::dev()->getItem(
            ["upload_max_size", "upload_slice_size", "upload_file_type", "upload_check_file_type","library_max_capacity"]
        );

        $upload_file_type = array_map(fn ($item) => explode(',', $item['type']) , $settings["upload_file_type"]);



        if ($settings['upload_check_file_type'] === 1  ){

            $upload_file_type_news = [];

            foreach( $upload_file_type as $val) $upload_file_type_news = array_merge($upload_file_type_news, $val);

            if(!in_array($this->params['file_type'], $upload_file_type_news)) return $this->outputEnum(Upload::UPLOAD_FILE_TYPE_ERROR);

        }

        if ($settings['upload_max_size'] * 1024 < $this->params['file_size'])  return $this->outputEnum(Upload::UPLOAD_FILE_SIZE_ERROR);


        if($this->params['is_common'] == 1){

            $capacity =  FileSlice::capacity($this->getAdminId(), $this->params['is_common']);

            if($capacity + $this->params['file_size'] > $settings['library_max_capacity'] * 1024 )  return $this->outputEnum(Upload::UPLOAD_CAP_OVER , [ 'cap' => Helper::fileUnit($settings['library_max_capacity'] * 1024) ]);

        }


        $admins_id = $this->getAdminId();

        $uuid = Uuid::createVersion4();

        ['file_url' =>  $file_url] = $this->createOssUrl($uuid, $this->params['dir_id'], $this->params['is_common'], $this->params['file_name']);

        $oid = FileSlice::insert(
            $admins_id,
            $this->params['is_common'],
            [
                'dir_id'    =>    $this->params['dir_id'],       //文件夹id
                'dir_link'    =>  $this->params['dir_link'],     //文件夹id上下级
                'file_size' =>    $this->params['file_size'],    //文件大小
                'admins_id' =>    $admins_id,                    //用户id
                'file_url'  =>    $file_url,                     //文件路径
                'file_type' =>    $this->params['file_type'],    //文件类型
                'file_name' =>    $this->params['file_name'],    //文件名称
            ]
        );

        return $this->output(['file_url' => $file_url, 'oid' => $oid], Upload::UPLOAD_FIRST_SUCCESS);
    }




    private  function  createOssUrl(string $uuid, string $dir_id, int $is_common, string $file_type)
    {

        $file =  $dir_id . '/' . $uuid . ($file_type ? '.' . Helper::getLastText($file_type, '.') : '');

        return ['file_url' => '/' . ($is_common === 0 ?  OssDirPrefix::ADMINS->value .  '/' . $this->getAdminId() . $file
            :   OssDirPrefix::COMMON->value . $file), 'file_type' =>   $file_type];
    }

    public function schedule()
    {
        FileSlice::schedule($this->getAdminId(), $this->params['is_common'], $this->params);
        return $this->outputEnum(Upload::SCHEDULE_CHANGE_SUCCESS);
    }


    public function list()
    {
        // 素材库容量大小
        $capacity =  FileSlice::capacity($this->getAdminId(), $this->params['is_common']);

        // 设置的素材库最大容量
        $settings = SettingServer::dev()->getItem(['library_max_capacity']);


        return $this->outputList(
            FileSlice::total(
                $this->getAdminId(),
                $this->params['is_common'],
                $this->params['dir_link'],
                $this->params['keyWord'],
                $this->params['file_type']
            ),
            FileSlice::list(
                $this->getAdminId(),
                $this->params['is_common'],
                $this->params['dir_link'],
                $this->params['pageNum'],
                $this->params['pageSize'],
                $this->params['keyWord'],
                $this->params['file_type'],
            ),
            [
                'capacity' => $capacity,
                'max_capacity' => $settings['library_max_capacity'] * 1024
            ]
        );
    }

    // createOssUrl(uuid: string , dir_id:string ,is_common : 1|0 , file_type:string ){
    // 			let file = `${dir_id}/${uuid}${file_type ? '.'+file_type : ''}`;
    // 			return is_common === 0 ? `/${this.dir_prefix?.admins}/${this.admins_id}/${file}` : `/${this.dir_prefix?.common}/${file}` ;
    // 		}
    public function followUp()
    {
        // UploadDirDao::add($this->params, $this->params['is_common'] ?  null : $this->getAdminId());
        // $admins_id = $this->getAdminId();
        // var_dump($this->params['oid']);

        // $res = FileSlice::find($admins_id, $this->params['oid']);
        // if(!$res)  return $this->outputError();
        // var_dump($res);
        // if(!$res) return  ;
        // return $this->outputSuccess([], ResultMsg::UPLOAD_SUCCESS);
    }

    public function getConfig()
    {
        $server = new OssServer;

        $settings =  $server->getSettings();

        $upload_config = Helper::formExtractData($settings, ["upload_file_type", "upload_check_file_type", "upload_max_size", "upload_slice_size"]);

        $oss_config = [];
        if ($settings['oss_start'] === 1) {   //oss Token请求
            $oss_config = $server->stsToken()->get();
            $oss_config['timeout'] = (int)$oss_config['timeout'];
            $oss_config['oss_bucket'] = $settings['oss_bucket'];
        }

        return $this->output([
            'upload' => $upload_config, 'oss' =>  $oss_config,
            'admins_id' => $this->getAdminId(),
            'dir_prefix' => [
                'common' =>  OssDirPrefix::COMMON->value,
                'admins' =>   OssDirPrefix::ADMINS->value,
            ]
        ], Success::SEL_SUCCESS);
    }


    public function stsMsg()
    {
        return $this->output(['uuid' =>   Uuid::createVersion4()], Success::CREATE_SUCCESS);
    }

    public function del()
    {

        $admins_id = $this->getAdminId();
        if ($this->params['real_del'] === 1) {
            //修改成等待删除状态
            FileSlice::update($admins_id,  $this->params['is_common'], $this->params['oids'] , ['wait_del' => 1]);
            foreach ($this->params['oids'] as $val) {
                 // 异步进队列删除
                dispatch((new ServiceJob([AdminsOss::class, 'del',[$admins_id, $this->params['is_common'], $val]],[]))->onConnection('rabbitmq')->onQueue('oss_del'));
            }
        } else {
            //软删除进回收站
            FileSlice::update($admins_id,  $this->params['is_common'], $this->params['oids'], ['is_del' => 1]);
        }
        return $this->outputEnum(Success::DEL_SUCCESS);
    }
}
